import {RouteRecordRaw,createRouter,createWebHistory} from 'vue-router'

import {ElMessage} from 'element-plus'
import api from '../api'
import dynicRoute from '../utils/dynicRoute'
const routes:Array<RouteRecordRaw>=[
    {
        path:'/login',
        component:()=>import('../views/Login.vue')
    },
    {
        path:'/',
        redirect:'/home'
    }
]
const router=createRouter({
    routes,
    history:createWebHistory()
})

//添加路由守卫
router.beforeEach(async(to,_,next)=>{
    if(to.path=="/login"){
        next()
    }else{
       const token=localStorage.getItem('token')
       if(token){
        try {
            await api.users.getUserInfo()
            dynicRoute()
            next()
        } catch (error) {
            ElMessage.warning("token失效，请重新登录")
            next("/login")
        }
     
       }else{
        ElMessage.warning('您还没登录，请先登录')
        next("/login")
       }
    }
    
    
})
export default router